/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.ormlite;

import java.lang.reflect.Field;
import java.sql.SQLException;

import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.field.SqlType;
import com.j256.ormlite.field.types.BaseEnumType;
import net.apexes.commons.lang.Enume;

/**
 * 
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 *
 * @param <T>
 * @param <E>
 */
public abstract class EnumeType<T extends Comparable<T>, E extends Enume<T>> extends BaseEnumType {
    
    private final Class<E> classType;
    
    /**
     * @param sqlType
     * @param classType
     */
    public EnumeType(SqlType sqlType, Class<E> classType) {
        super(sqlType, new Class<?>[] { classType });
        this.classType = classType; 
    }

    @Override
    public boolean isValidForField(Field field) {
        return classType.isAssignableFrom(field.getType());
    }

    @Override
    public Object javaToSqlArg(FieldType fieldType, Object obj) throws SQLException {
        @SuppressWarnings("unchecked")
        E enume = (E) obj;
        return Enume.toValue(enume);
    }

    @Override
    public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) throws SQLException {
        @SuppressWarnings("unchecked")
        E enume = Enume.fromValue(classType, (T)sqlArg);
        return enume;
    }

}
